# -*- coding: utf-8 -*-
# @Author  : lxd
# @Time    : 2025/7/22
# @Function: 根据category_id删除QA数据

import psycopg2
from loguru import logger
from config import DB_CONFIG


class QADeleter:
    def __init__(self, db_config: dict):
        """初始化QA删除器

        Args:
            db_config (dict): 数据库连接配置
        """
        self.db_config = db_config
        self.conn = None

    def connect_db(self):
        """连接数据库"""
        try:
            self.conn = psycopg2.connect(**self.db_config)
            logger.info("数据库连接成功")
        except Exception as e:
            logger.error(f"数据库连接失败: {e}")
            raise

    def delete_by_category_id(self, category_id: str):
        """根据category_id删除QA数据

        Args:
            category_id (str): 要删除的数据所属的类别ID
        """
        delete_sql = "DELETE FROM qa_knowledge WHERE category_id = %s;"

        try:
            with self.conn.cursor() as cursor:
                cursor.execute(delete_sql, (category_id,))
                deleted_rows = cursor.rowcount
                self.conn.commit()
                logger.info(f"成功删除 {deleted_rows} 条 category_id 为 '{category_id}' 的数据")
                return deleted_rows
        except Exception as e:
            logger.error(f"根据 category_id 删除数据失败: {e}")
            self.conn.rollback()
            raise

    def run(self, category_id: str):
        """执行删除操作

        Args:
            category_id (str): 要删除的数据所属的类别ID
        """
        try:
            self.connect_db()
            self.delete_by_category_id(category_id)
        except Exception as e:
            logger.error(f"删除操作执行失败: {e}")
        finally:
            if self.conn:
                self.conn.close()
                logger.info("数据库连接已关闭")


def main():
    """主函数"""
    # 数据库配置
    db_config = DB_CONFIG

    # 要删除的 category_id
    # ##################################
    # # 请在这里修改为您要删除的 category_id #
    # ##################################
    category_id_to_delete = "21100150"

    if not category_id_to_delete:
        logger.warning("未指定要删除的 category_id，程序退出。")
        return

    # 创建删除器并执行删除
    deleter = QADeleter(db_config)
    deleter.run(category_id_to_delete)


if __name__ == "__main__":
    main()
